package com.cheung.leetcode.stackandqueue;

import org.junit.jupiter.api.Test;

import java.util.List;
import java.util.Stack;

/**
 * @BelongsProject : java-leetcode
 * @BelongsPackage : com.cheung.leetcode.stackandqueue
 * @Author :  cheungming
 * @CreateTime : 2024-05-12 10:28:08
 * @Description : 逆波兰表达式——也就是后缀表达式
 * 波兰表达式是前缀表达式
 * @Version : 1.0
 */
public class Code150Test {

    public int evalRPN(String[] tokens) {
        List<String> operator = List.of("+", "-", "*", "/");
        Stack<String> stack = new Stack<>();
        for (String token : tokens) {
            if (operator.contains(token)) {
                int b = Integer.parseInt(stack.pop());
                int a = Integer.parseInt(stack.pop());

                int c = switch (token) {
                    case "+" -> a + b;
                    case "-" -> a - b;
                    case "*" -> a * b;
                    case "/" -> a / b;
                    default -> 0;
                };

                stack.push(String.valueOf(c));

            } else {
                stack.push(token);
            }
        }

        return Integer.parseInt(stack.pop());
    }


    @Test
    public void test1() {
        String[] tokens = {"2", "1", "+", "3", "*"};
        assert 9 == evalRPN(tokens);
    }


    @Test
    public void test2() {
        String[] tokens = {"4", "13", "5", "/", "+"};
        assert 6 == evalRPN(tokens);
    }


    @Test
    public void test3() {
        String[] tokens = {"10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+"};
        assert 22 == evalRPN(tokens);
    }
}
